package edu.jd.common;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.*;

public class Utils {
    private static final String MYBATIS_CONFIG = "mybatis.xml";
    private static final SqlSessionFactory FACTORY = buildFactory();

    public static SqlSessionFactory buildFactory(){
        InputStream in = null;
        try {
            in = Resources.getResourceAsStream(MYBATIS_CONFIG);
            return new SqlSessionFactoryBuilder().build(in);
        } catch (IOException e) {
            e.printStackTrace();
            //RuntimeException是非受检异常
            throw new RuntimeException("创建session工厂失败", e);
        }
    }

    public static SqlSessionFactory getFactory(){
        return FACTORY;
    }

    public static SqlSession openSession(){
        return FACTORY.openSession();
    }
}
